// 1.匹配不以'/'或者'.html'结尾的请求，并重定向到以斜杠结尾的情况
// 此处很容易重定向产生问题，需要优化
const path = require('path')
const resolve = file => path.resolve(__dirname, file)
const fs = require('fs')

const config = require(resolve('../config/env'))
const assetsPath = fs.readdirSync(path.resolve(__dirname,'../assets'))

module.exports = (req, res, next) => {
  let url = req.url
  // 接口请求不会重定向
  let whiteArr = config.proxyArr
  if (whiteArr.some(item => url.includes(item.proxy))) return next()
  if(assetsPath.some(item => url.includes(item))) return next()
  //本地__webpack_hmr不重定向 报错 EventSource's response has a MIME type ("text/html") that is not "text/event-stream". Aborting the connection.
  if(url.includes('__webpack_hmr')) return next()
  let urlArr = url && url.split('?')
  let lastUrl = urlArr[0] + '\/' + (urlArr[1] ? '?' + urlArr[1] : '')
  let reg = /\..+$/
  if (urlArr[0].startsWith('/news/ac/')  || urlArr[0].startsWith('/ac/') || reg.test(urlArr[0]) || urlArr[0].endsWith('/') || urlArr[0].includes('/sem/') || urlArr[0].includes('/sem_')) {
    next()
  } else {
    res.redirect(301,lastUrl)
    return
  }
}